package com.sky.task;

import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.Orders;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2024/10/19 9:12
 * @Version 1.0
 */
@Component
@Slf4j
public class OrderPayCheckTask {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private Config config;
    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkOrderPayStatus(){
        log.info("检查支付超时订单任务开始");
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("checkOrderPayStatus", "1",Duration.ofSeconds(10));
        if(!lock){
            log.info("未获取到锁，不执行");
            return;
        }
        try {
            long start = System.currentTimeMillis();
            //要数据库里面找：找一直处于待支付的订单  15分钟前的订单
            LocalDateTime before15Min = LocalDateTime.now().minusMinutes(15);
            List<Orders> checkPayStatusOrders = orderMapper.getCheckPayStatusOrders(before15Min);
            if (CollectionUtils.isEmpty(checkPayStatusOrders)) {
                log.info("没有需要处理的订单");
                return;
            }
            for (Orders checkPayStatusOrder : checkPayStatusOrders) {
                Boolean flag = getPayStatusFromWX(checkPayStatusOrder.getNumber());
                //支付成功，更改订单状态和支付状态
                if (flag) {
                    checkPayStatusOrder.setStatus(Orders.TO_BE_CONFIRMED);
                    checkPayStatusOrder.setPayStatus(Orders.PAID);
                    orderMapper.updateOrderPaySuccess(checkPayStatusOrder);
                } else {
                    checkPayStatusOrder.setStatus(Orders.CANCELLED_ORDER);
                    checkPayStatusOrder.setCancelTime(LocalDateTime.now());
                    checkPayStatusOrder.setCancelReason("超时未支付");
                    orderMapper.cancelOrder(checkPayStatusOrder);
                }
            }
            long end = System.currentTimeMillis();
            log.info("检查支付超时订单任务完成,耗时：{}秒",(end - start)/1000);
        }finally {
            redisTemplate.delete("checkOrderPayStatus");
        }
    }


    private boolean getPayStatusFromWX(String orderNo){
        try {
            QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
            request.setMchid("1561414331");
            request.setOutTradeNo(orderNo);

            NativePayService payService = new NativePayService.Builder().config(config).build();
            Transaction transaction = payService.queryOrderByOutTradeNo(request);
            log.info("调用微信查询接口返回：{}", transaction);
            if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
                return true;
            }
        }catch (ServiceException e){
            if(e.getErrorCode().equals("ORDER_NOT_EXIST")){
                log.info("微信订单不存在，没有发起过支付");
                return false;
            }
        }
        return false;
    }
}